<?php

namespace app\backstage\controller;
header("Content-type: text/html; charset=utf-8");

use think\Request;
use app\backstage\model\ResourceFile;
use app\backstage\model\ResourceFolder;
use Db;

class Resource extends BaseAuth
{





    //上传视频  分片上传
    public function webUpload(Request $request,ResourceFile $resource)
    {

        if (request()->isPost()) {

            $data = input('post.');

            // 成功上传后 获取上传信息
            $insertData = array(
                'file_name' => $data['file_name'],
                'file_path' => $data['file_path'],
                'type' => $data['type'],
                'admin_id' => $request->admin_id,
                'folder_id' =>$data['folder_id']?:0,
                'create_time' => time()
            );

            $in = $resource->insert($insertData);

            if($in){

                $this->success('保存成功');
            }else{
                $this->success('保存失败');

            }
        }

        $type= input('type');
        switch ($type) {
            case 1:
                $path = 'images/';
                break;
            case 2:
                $path = 'audio/';
                break;
            case 3:
                $path = 'video/';
                break;
            default:
                $path = 'file/';
        }

        $dir = $path.date('Ymd');

        return view('web_upload', ['dir'=>$dir,'type' => input('type',1), 'folder_id' => input('folder_id',0)]);
//        return view('web_upload', ['type' => input('type',1), 'folder_id' => input('folder_id',0), 'time' => time() . uniqid()]);

    }




    //上传视频  分片上传
    public function webUpload2($path = 'file')
    {

        if (request()->isPost()) {

            set_time_limit(30);
            $post = $_POST;
            $file = $_FILES;

            $type= input('file_type');
            switch ($type) {
                case 1:
                    $path = 'images';
                    break;
                case 2:
                    $path = 'audio';
                    break;
                case 3:
                    $path = 'video';
                    break;
            }

            // 建立临时目录存放文件-以MD5为唯一标识
            $dir = 'upload/' . $path . '/' . date('Ymd');

            if (!is_dir($dir)) {
                mkdir($dir);
            }


            if (empty($post['chunk'])) {
                $post["chunk"] = 0;
            }

            $file_name = input('time');
            $dir .= '/' . $file_name;
            if (!is_dir($dir)) {
                mkdir($dir);
            }

            if (!file_exists($dir)) {
                mkdir($dir);
            }

            // 移入缓存文件保存
            $res = move_uploaded_file($file["file"]["tmp_name"], $dir . '/' . $post["chunk"]);

            return json(['code'=>1,'dir'=>$dir]);

//        if($post['chunk']+1==$post['chunks']){
//
//            $filesnames = scandir($dir);                         //scandir() 函数返回指定目录中的文件和目录的数组。默认升序排列，
//
//            $type = strrchr($file["file"]["name"],'.');
//
//            foreach ($filesnames as $name) {
//
//                if ($name != ".." && $name != ".")                   //遍历结果中会多出‘.’以及‘..’，没有用处，不予处理;
//                {
//                    $file_name = $dir . '/' . $name;
//
//                    $str = file_get_contents($file_name);
//                    file_put_contents($dir .$type, $str, FILE_APPEND);
//                }
//            }
//
//            @rmdir($dir);
//
//            return '/'.$dir.$type;
//        }

        }

        $type= input('type');
        switch ($type) {
            case 1:
                $path = 'images/';
                break;
            case 2:
                $path = 'audio/';
                break;
            case 3:
                $path = 'video/';
                break;
            default:
                $path = 'file/';
        }

        $dir = $path.date('Ymd');

        return view('web_upload', ['dir'=>$dir,'type' => input('type',1), 'folder_id' => input('folder_id',0)]);
//        return view('web_upload', ['type' => input('type',1), 'folder_id' => input('folder_id',0), 'time' => time() . uniqid()]);

    }


    //合并分片文件文件
    public function mergeFile(Request $request,ResourceFile $resource)
    {

        $dir = input('dir');
        $type = input('file_type', 1);

        $filesnames = scandir($dir);                         //scandir() 函数返回指定目录中的文件和目录的数组。默认升序排列，

        asort($filesnames);
        $ext = '.'.input('ext','mp4');


        foreach ($filesnames as $name) {
            $file_name = $dir . '/' . $name;

            if ($name != ".." && $name != ".")                   //遍历结果中会多出‘.’以及‘..’，没有用处，不予处理;
            {

                $str = file_get_contents($file_name);
                file_put_contents($dir . $ext, $str, FILE_APPEND);
            }

            @unlink($file_name);

        }

        switch ($type) {
            case 1:
                $file_type = 'images/';
                break;
            case 2:
                $file_type = 'audio/';
                break;
            case 3:
                $file_type = 'video/';
                break;
        }


        $tmp_name = $dir .$ext;
        // 移动到框架应用根目录/uploads/ 目录下
        $folder = $file_type . date('Ymd');

        $info = ossUpload($folder, $tmp_name, $ext);

        if ($info) {
            $file_name = input('file_name',$tmp_name);

            // 成功上传后 获取上传信息
            $insertData = array(
                'file_name' => $file_name,
                'file_path' => $info['file_name'],
                'type' => $type,
                'admin_id' => $request->admin_id,
                'folder_id' => $request->param('folder_id'),
                'create_time' => time()
            );

            $in = $resource->insert($insertData);

            if ($in) {
//                    if(empty($insertData['folder_id'])){
//                        return json(['errno'=>0,'data'=>[config('api.oss_img_path').$info['file_name']]]);
//                    }
                return json(['code' => 1, 'msg' => 'success', 'file_name' => $file_name]);
            } else {
//                    unlink('uploads/'.$filePath);
                return ['code' => 0, 'msg' => '文件保存失败'];

            }

        } else {
            // 上传失败获取错误信息
            return json(['code' => 0, 'msg' => '上传失败']);

        }

        @rmdir($dir);

        return json(['code' => 1, 'path' => '/' . $dir . $ext]);


    }


    /**
     * 显示图片文件夹
     *
     * @return \think\Response
     */
    public function image_folder(Request $request, ResourceFolder $resource)
    {

        $sel = $request->param('sel');

        return view('folder_list', ['folder_type' => 1, 'sel' => $sel]);
    }


    /**
     * 获取文件夹列表
     *
     * @return \think\Response
     */
    public function folder_list(Request $request, ResourceFolder $resource)
    {

        $type = input('folder_type');

        if ($type && $request->isAjax()) {
            $data = $resource->field('id,folder_name')->where(['type' => $type, 'admin_id' => $request->admin_id])->select();

            $default = ['id' => 0, 'folder_name' => '默认文件夹'];
//          array_push($data,$default);
            $data[] = $default;
            return ['code' => 200, 'data' => $data];
        }

        $sel = $request->param('sel');

        return view('folder_list', ['folder_type' => $type, 'sel' => $sel]);

    }


    /**
     * 创建文件夹
     *
     * @return \think\Response
     */
    public function create_folder($folder_type, Request $request, ResourceFolder $resource)
    {


        if ($folder_name = $request->post('folder_name')) {

            $inData = array(
                'folder_name' => $folder_name,
                'type' => $folder_type,
                'admin_id' => $request->admin_id,
                'create_time' => time()
            );

            $in = $resource->insert($inData);

            if ($in) {
                return ['code' => 200];
            } else {
                return ['code' => 100, 'msg' => '创建失败'];
            }
        }

        return view('create_folder', ['folder_type' => $folder_type]);
    }

    /**
     * 删除文件夹
     */
    public function delete_folder(Request $request, ResourceFolder $resource, ResourceFile $file)
    {

        if ($ids = $request->param('ids')) {


            Db::startTrans();
            $res = $resource->whereIn('id', $ids)->delete();

            if ($res) {

                $files = $file->whereIn('folder_id', $ids)->select();

                if (count($files) > 0) {
                    // dump($files);
                    //删除包含的文件
                    $res = $file->whereIn('folder_id', $ids)->delete();
                    foreach ($files as $v) {
//                        $v['file_path']=iconv('utf-8', 'gbk', $v['file_path']);
//                        if(file_exists('uploads/'.$v['file_path'])){
//                            unlink('uploads/'.$v['file_path']);
//                        }
                        //从云上删除
                        ossDeleteFile($v['file_path']);
                    }
                }

                if ($res) {
                    Db::commit();
                    return ['code' => 200];
                } else {
                    Db::rollback();
                    return ['code' => 100, 'msg' => '删除文件失败'];
                }

            } else {
                return ['code' => 100, 'msg' => '删除失败'];

            }

        } else {

            return ['code' => 100, 'msg' => '参数有误'];
        }
    }

    /**
     * 修改文件夹名称
     */
    public function update_folder_name(Request $request, ResourceFolder $resource)
    {

        if ($request->param('id') && $request->param('folder_name')) {

            $res = $resource->where('id', $request->param('id'))->update(['folder_name' => $request->param('folder_name')]);

            return ['code' => 200];

        } else {

            return ['code' => 100, 'msg' => '参数有误'];
        }
    }

    /**
     * 显示文件列表
     *
     * @return \think\Response
     */
    public function file_list(Request $request, ResourceFile $resource)
    {

        $type = input('type', 1);


        if ($request->isAjax()) {
            //分页
            $pageSize = 15;
            $params = input('get.');


            $page = $params['page'] ?: 1;
            $offset = ($page - 1) * $pageSize;
            $where = [
//                 ['admin_id','=',$request->admin_id],
                ['folder_id', '=', $params['folder_id']],
                ['type', '=', $type],

            ];


            //搜索
            if (!empty($params['start'])) {
                $where[] = ['create_time', '>=', strtotime($params['start'])];
            }

            if (!empty($params['end'])) {
                $where[] = ['create_time', '<=', strtotime($params['end'])];
            }

            if (!empty($params['seach_text'])) {
                $where[] = ['file_path', 'like', "%{$params['seach_text']}%"];
            }


            //图片列表
            $data = $resource->where($where)->order('id', 'desc')->limit($offset, $pageSize)->select();

            $count = $resource->where($where)->count();

            $pageData = ['count' => $count, 'page' => (int)$page, 'pageSize' => $pageSize];

            if ($data) {
                foreach ($data as &$v) {
                    $v['create_time'] = date('Y-m-d H:i', $v['create_time']);
                    $v['file_path'] = $v['file_path'];
                    //  if(mb_strlen($v['file_name']>20)){
                    //      $v['file_name'] = mb_substr($v['file_name'],0,20).'...';
                    //  }
                }
            }

            return ['code' => 200, 'fileList' => $data, 'pageData' => $pageData];
        }


        if ($sel = $request->param('sel')) {
            return view('file_select_list', ['folder_id' => $request->param('folder_id'), 'sel' => $sel, 'type' => $type]);
        }

        return view('file_list', ['folder_id' => $request->param('folder_id'), 'type' => $type]);
    }


    /**
     * 上传单张图片到阿里云oss
     *
     * @return \think\Response
     */
    public function upload_file(Request $request, ResourceFile $resource)
    {

        if ($request->isPost()) {

            $type = input('type', 1);

            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file();

            $file = array_shift($file);

            $fileInfo = $file->getInfo();

            $tmp_name = $fileInfo['tmp_name'];

            $fileName = $fileInfo['name'];

            switch ($type) {
                case 1:
                    $file_type = 'images/';
                    break;
                case 2:
                    $file_type = 'audio/';
                    break;
                case 3:
                    $file_type = 'video/';
                    break;
            }


            // 移动到框架应用根目录/uploads/ 目录下
            $folder = $file_type . date('Ymd');

            $info = ossUploadFile($folder, $tmp_name, strrchr($fileInfo['name'], '.'));

            if ($info) {

                // 成功上传后 获取上传信息
                $insertData = array(
                    'file_name' => $fileName,
                    'file_path' => $info['file_name'],
                    'type' => $type,
                    'admin_id' => $request->admin_id,
                    'folder_id' => input('folder_id',0),
                    'create_time' => time()
                );

                $in = $resource->insert($insertData);

                if ($in) {
                    if(empty($insertData['folder_id'])){
                        return json(['errno'=>0,'data'=>[config('api.oss_img_path').$info['file_name']]]);
                    }
                    return json(['code' => 200, 'msg' => 'success', 'file_name' => $fileName]);
                } else {
//                    unlink('uploads/'.$filePath);
                    return json(['code' => 100, 'msg' => '文件保存失败']);

                }

            } else {
                // 上传失败获取错误信息
                return json(['code' => 200, 'msg' => $file->getError()]);

            }

        }

        return view('upload_file', ['folder_id' => $request->param('folder_id'), 'type' => $request->param('type')]);
    }

    /**
     * 上传单张图片到本地
     *
     * @return \think\Response
     */
    public function upload_image_local(Request $request, ResourceFile $resource)
    {

        if ($request->isPost()) {

            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');

            $fileName = $file->getInfo()['name'];

            // 移动到框架应用根目录/uploads/ 目录下
            $fileName = date('His') . '_' . $fileName;
            $filePath = date('Ymd') . '/' . $fileName;
//            $info = $file->move( 'uploads', iconv('UTF-8','GBK//IGNORE',$filePath),false);
            $info = $file->move('uploads', $filePath, false);
            if ($info) {

                // 成功上传后 获取上传信息
                $insertData = array(
                    'file_name' => $fileName,
                    'file_path' => $filePath,
                    'type' => 1,
                    'admin_id' => $request->admin_id,
                    'folder_id' => $request->param('folder_id'),
                    'create_time' => time()
                );

                $in = $resource->insert($insertData);

                if ($in) {
                    return ['code' => 200, 'msg' => 'success', 'file_name' => $fileName];
                } else {
                    unlink('uploads/' . $filePath);
                    return ['code' => 100, 'msg' => '保存图片失败'];

                }

            } else {
                // 上传失败获取错误信息
                return ['code' => 200, 'msg' => $file->getError()];

            }

        }

        return view('show_upload_image', ['folder_id' => $request->param('folder_id'), 'type' => $request->param('type')]);
    }


    public function upload_image_all()
    {

    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {

        $res = ResourceFile::destroy($id);

        if ($res) {
            return ['code' => 200];
        } else {
            return ['code' => 101, 'msg' => '删除失败'];
        }
    }


    /**
     * 批量删除
     *
     * @param  string $ids
     * @return \think\Response
     */
    public function delete_all()
    {

        if ($ids = request()->post('ids')) {

            $files = ResourceFile::whereIn('id', $ids)->select();

            if ($files) {
                $res = ResourceFile::destroy($ids);

                foreach ($files as $v) {
//                    $v['file_path']=iconv('utf-8', 'gbk', $v['file_path']);
//                    if(file_exists('uploads/'.$v['file_path'])){
//                        unlink('uploads/'.$v['file_path']);
//                    }

                    //从云上删除
                    ossDeleteFile($v['file_path']);

                }
            }

            if ($res) {
                return ['code' => 200];
            } else {
                return ['code' => 101, 'msg' => '删除失败'];
            }
        } else {
            return ['code' => 101, 'msg' => '缺少参数'];
        }

    }
}
